package management

import (
	"context"
	"encoding/json"
	"fmt"
	"log"
	"net/http"
	"reflect"
	"strconv"
	"strings"
	"time"

	"github.com/gorilla/mux"
	"github.com/jsrccb/nachuan/common"
	"github.com/tealeg/xlsx"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/bson/primitive"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
	"go.mongodb.org/mongo-driver/x/bsonx"
)

type ClueMgr struct {
	client            *mongo.Client
	clueCollection    *mongo.Collection
	entclueCollection *mongo.Collection
}

var (
	G_clueMgr *ClueMgr
)

func initClueApi(r *mux.Router) {
	s := r.PathPrefix("/clue").Subrouter()
	// s.HandleFunc("/list", UserListHandler)
	s.HandleFunc("/updsave", handleClueInfo)
	s.HandleFunc("/del", handleDelClueInfo)
	s.HandleFunc("/drop", handleDropClueInfo)
	//请求/clue/query?clueno=xxx
	s.HandleFunc("/query", handleQueryClueInfo2)
	//请求超时未追踪线索
	s.HandleFunc("/queryoutofline", handleQueryClueInfoOutOfLine)
	s.HandleFunc("/download", handleDownloadClueInfo)
	s.HandleFunc("/opercluefloor", handleOperatingClueFloor)
	s.HandleFunc("/operFQcluefloor", handleOperatingFQClueFloor)
	// s.HandleFunc("/opercluefloor2", queryOperatingFloor)

	ents := r.PathPrefix("/entclue").Subrouter()
	// s.HandleFunc("/list", UserListHandler)
	ents.HandleFunc("/updsave", handleEntClueInfo)
	// ents.HandleFunc("/del", handleDelClueInfo)
	//请求/clue/query?clueno=xxx
	ents.HandleFunc("/query", handleQueryEntClueInfo)
	ents.HandleFunc("/updenvcluests", handleUpdEntClueSts)
	ents.HandleFunc("/draw", handleDrawEntClueInfo) //领取
	ents.HandleFunc("/query", handleQueryEntClueInfo)
	ents.HandleFunc("/trace", handleTraceEntClue)

	//请求/user/queryall?skip=0&limit=10
	// s.HandleFunc("/queryall", handlePartAll)
}
func handleOperatingFQClueFloor(resp http.ResponseWriter, req *http.Request) {
	var (
		err   error
		bytes []byte
		// entcluests  string
		// rolelimit     *common.RoleLimits

		mon1cluecount     int64 //流失一个月内
		mon3cluecount     int64 //流失三个月内
		mon6cluecount     int64 //流失6个月内
		mon9cluecount     int64 //流失9个月内
		year1cluecount    int64 //流失1年内
		year2cluecount    int64 //流失2年内
		yearout2cluecount int64 //流失2年外
	)

	t := time.Now() // 获取当前时间
	// m := t.Format("2006-01-02") //获取当前格式的日期
	// beforeDay := t.AddDate(0,0,-1)  // 三个参数分别是年月日，此处获取的是前一天的日期
	before1Month := t.AddDate(0, -1, 0) // 前一个月的日期
	before3Month := t.AddDate(0, -3, 0) // 前一个月的日期
	before6Month := t.AddDate(0, -6, 0) // 前一个月的日期
	before9Month := t.AddDate(0, -9, 0) // 前一个月的日期
	before1year := t.AddDate(-1, 0, 0)  // 前一个月的日期
	before2year := t.AddDate(-2, 0, 0)  // 前一个月的日期
	// before1Month.Format("2006-01-02")
	// beforeYear := t.AddDate(-1,0,0)  // 去年的当天日期
	// fmt.Println(beforeDay,beforeMonth,beforYear,m)
	// fmt.Println(beforeDay.Format("2006-01-02 15:04:05"))

	cluemap := make(map[string]interface{})

	if mon1cluecount, err = G_clueMgr.queryOperatingFQClueCountbyDate(before1Month.Format("2006-01-02"), common.BuildDateTodayStr2()); err != nil {
		goto ERR
	}
	if mon3cluecount, err = G_clueMgr.queryOperatingFQClueCountbyDate(before3Month.Format("2006-01-02"), before1Month.Format("2006-01-02")); err != nil {
		goto ERR
	}
	if mon6cluecount, err = G_clueMgr.queryOperatingFQClueCountbyDate(before6Month.Format("2006-01-02"), before3Month.Format("2006-01-02")); err != nil {
		goto ERR
	}
	if mon9cluecount, err = G_clueMgr.queryOperatingFQClueCountbyDate(before9Month.Format("2006-01-02"), before6Month.Format("2006-01-02")); err != nil {
		goto ERR
	}
	if year1cluecount, err = G_clueMgr.queryOperatingFQClueCountbyDate(before1year.Format("2006-01-02"), before9Month.Format("2006-01-02")); err != nil {
		goto ERR
	}
	if year2cluecount, err = G_clueMgr.queryOperatingFQClueCountbyDate(before2year.Format("2006-01-02"), before1year.Format("2006-01-02")); err != nil {
		goto ERR
	}
	if yearout2cluecount, err = G_clueMgr.queryOperatingFQClueCountbyDate("2000-01-01", before2year.Format("2006-01-02")); err != nil {
		goto ERR
	}

	cluemap["mon1cluecount"] = mon1cluecount
	cluemap["mon3cluecount"] = mon3cluecount
	cluemap["mon6cluecount"] = mon6cluecount
	cluemap["mon9cluecount"] = mon9cluecount
	cluemap["year1cluecount"] = year1cluecount
	cluemap["year2cluecount"] = year2cluecount
	cluemap["yearout2cluecount"] = yearout2cluecount

	if bytes, err = common.BuildResponse(0, "success", cluemap); err == nil {
		resp.Write(bytes)
	} else {
		goto ERR
	}

	return
ERR:
	if bytes, err = common.BuildResponse(-1, err.Error(), nil); err == nil {
		resp.Write(bytes)
	}
}

//今日待追踪线索count for IncustomMgr
func (clueMgr *ClueMgr) queryOperatingFQClueCountbyDate(beginDate string, endDate string) (todaytracecount int64, err error) {

	var (
		ctx context.Context
		// results  []bson.M
		// doccount int64
	)
	ctx, _ = context.WithTimeout(context.Background(), 10*time.Second)

	// if todaytracecount, err = clueMgr.clueCollection.CountDocuments(ctx, bson.M{"clueStatus": "跟进中", "channelType": "内部员工发掘", "nextTraceDate": common.BuildDateTodayStr2()}, &options.CountOptions{}); err != nil {
	filter := bson.D{{"$and", []interface{}{bson.M{"nextTraceDate": bson.M{"$gte": beginDate}}, bson.M{"nextTraceDate": bson.M{"$lte": endDate}}, bson.M{"clueStatus": "废弃"}}}}

	if todaytracecount, err = clueMgr.clueCollection.CountDocuments(ctx, filter, &options.CountOptions{}); err != nil {
		todaytracecount = 0
	}
	return
}

func handleOperatingClueFloor(resp http.ResponseWriter, req *http.Request) {
	var (
		err   error
		bytes []byte
		// entcluests  string
		custommgr string
		// rolelimit     *common.RoleLimits

		todaycluetracecount int64 //今天待追踪
		todaycluecount      int64 //今日线索
		moncluecount        int64 //本月线索
		monYXcluecount      int64 //本月营销发掘线索
		monXScluecount      int64 //本月销售发掘线索
		monNBYGcluecount    int64 //本月内部员工发掘线索
		monBDcluecount      int64 //本月百度线索
		monDYcluecount      int64 //本月抖音线索
		mon58cluecount      int64 //本月58同城线索
		acluetracecount     int64 //A类待追踪
		bcluetracecount     int64 //B类待追踪
		ccluetracecount     int64 //C类待追踪
		ecluetracecount     int64 //E类待追踪
		hdcluetracecount    int64 //获得线索
	)
	cluemap := make(map[string]interface{})

	query := req.URL.Query()
	custommgr = query.Get("custommgr")

	if custommgr == "内部员工发掘" {
		if todaycluetracecount, err = G_clueMgr.queryOperatingTodayTraceClueCountForInCustomMgr(); err != nil {
			goto ERR
		}
		if todaycluecount, err = G_clueMgr.getOperatingCuleSumTodayForInCustomMgr(); err != nil {
			goto ERR
		}
		if moncluecount, err = G_clueMgr.getOperatingCuleSumMonForInCustom(); err != nil {
			goto ERR
		}

	} else if custommgr != "" && custommgr != "内部员工发掘" {
		if todaycluetracecount, err = G_clueMgr.queryOperatingTodayTraceClueCountForCustomMgr(custommgr); err != nil {
			goto ERR
		}
		if todaycluecount, err = G_clueMgr.getOperatingCuleSumTodayForCustomMgr(custommgr); err != nil {
			goto ERR
		}
		if moncluecount, err = G_clueMgr.getOperatingCuleSumMonForCustom(custommgr); err != nil {
			goto ERR
		}
		if acluetracecount, err = G_clueMgr.queryAClueOperatingTodayTraceClueCountForCustomMgr(custommgr); err != nil {
			goto ERR
		}
		if bcluetracecount, err = G_clueMgr.queryBClueOperatingTodayTraceClueCountForCustomMgr(custommgr); err != nil {
			goto ERR
		}
		if ccluetracecount, err = G_clueMgr.queryCClueOperatingTodayTraceClueCountForCustomMgr(custommgr); err != nil {
			goto ERR
		}
		if ecluetracecount, err = G_clueMgr.queryEClueOperatingTodayTraceClueCountForCustomMgr(custommgr); err != nil {
			goto ERR
		}
		if hdcluetracecount, err = G_clueMgr.queryHDClueOperatingTodayTraceClueCountForCustomMgr(custommgr); err != nil {
			goto ERR
		}
	} else if custommgr == "" {
		if todaycluetracecount, err = G_clueMgr.queryOperatingTodayTraceClueCount(); err != nil {
			goto ERR
		}
		if todaycluecount, err = G_clueMgr.getOperatingCuleSumToday(); err != nil {
			goto ERR
		}
		if moncluecount, err = G_clueMgr.getOperatingCuleSumMon(); err != nil {
			goto ERR
		}
		if acluetracecount, err = G_clueMgr.queryAClueOperatingTodayTraceClueCount(); err != nil {
			goto ERR
		}
		if bcluetracecount, err = G_clueMgr.queryBClueOperatingTodayTraceClueCount(); err != nil {
			goto ERR
		}
		if ccluetracecount, err = G_clueMgr.queryCClueOperatingTodayTraceClueCount(); err != nil {
			goto ERR
		}
		if ecluetracecount, err = G_clueMgr.queryEClueOperatingTodayTraceClueCount(); err != nil {
			goto ERR
		}
		if hdcluetracecount, err = G_clueMgr.queryHDClueOperatingTodayTraceClueCount(); err != nil {
			goto ERR
		}
	}

	if monYXcluecount, err = G_clueMgr.getOperatingClueYXMon(); err != nil {
		goto ERR
	}
	if monXScluecount, err = G_clueMgr.getOperatingCuleXSMon(); err != nil {
		goto ERR
	}
	if monNBYGcluecount, err = G_clueMgr.getOperatingCuleNBYGMon(); err != nil {
		goto ERR
	}
	if monBDcluecount, err = G_clueMgr.getOperatingCuleBDMon(); err != nil {
		goto ERR
	}
	if monDYcluecount, err = G_clueMgr.getOperatingCuleDYMon(); err != nil {
		goto ERR
	}
	if mon58cluecount, err = G_clueMgr.getOperatingCule58Mon(); err != nil {
		goto ERR
	}

	cluemap["todaycluetracecount"] = todaycluetracecount
	cluemap["todaycluecount"] = todaycluecount
	cluemap["moncluecount"] = moncluecount
	cluemap["monYXcluecount"] = monYXcluecount
	cluemap["monXScluecount"] = monXScluecount
	cluemap["monNBYGcluecount"] = monNBYGcluecount
	cluemap["monBDcluecount"] = monBDcluecount
	cluemap["mon58cluecount"] = mon58cluecount
	cluemap["monDYcluecount"] = monDYcluecount

	cluemap["acluetracecount"] = acluetracecount
	cluemap["bcluetracecount"] = bcluetracecount
	cluemap["ccluetracecount"] = ccluetracecount
	cluemap["ecluetracecount"] = ecluetracecount
	cluemap["hdcluetracecount"] = hdcluetracecount

	if bytes, err = common.BuildResponse(0, "success", cluemap); err == nil {
		resp.Write(bytes)
	} else {
		goto ERR
	}

	return
ERR:
	if bytes, err = common.BuildResponse(-1, err.Error(), nil); err == nil {
		resp.Write(bytes)
	}
}

//今日待追踪线索count for IncustomMgr
func (clueMgr *ClueMgr) queryOperatingTodayTraceClueCountForInCustomMgr() (todaytracecount int64, err error) {

	var (
		ctx context.Context
		// results  []bson.M
		// doccount int64
	)
	ctx, _ = context.WithTimeout(context.Background(), 10*time.Second)

	// if todaytracecount, err = clueMgr.clueCollection.CountDocuments(ctx, bson.M{"clueStatus": "跟进中", "channelType": "内部员工发掘", "nextTraceDate": common.BuildDateTodayStr2()}, &options.CountOptions{}); err != nil {

	if todaytracecount, err = clueMgr.clueCollection.CountDocuments(ctx, bson.M{"clueStatus": "跟进中", "channelType": "内部员工发掘", "nextTraceDate": bson.M{"$lte": common.BuildDateTodayStr2()}}, &options.CountOptions{}); err != nil {
		todaytracecount = 0
	}
	return
}

//今日待追踪线索count for customMgr
func (clueMgr *ClueMgr) queryOperatingTodayTraceClueCountForCustomMgr(customMgr string) (todaytracecount int64, err error) {

	var (
		ctx context.Context
		// results  []bson.M
		// doccount int64
	)
	ctx, _ = context.WithTimeout(context.Background(), 10*time.Second)

	if todaytracecount, err = clueMgr.clueCollection.CountDocuments(ctx, bson.M{"clueStatus": "跟进中", "clueType": bson.M{"$ne": "E类:对接同行"}, "customMgr": customMgr, "nextTraceDate": bson.M{"$lte": common.BuildDateTodayStr2()}}, &options.CountOptions{}); err != nil {
		todaytracecount = 0
	}
	// fmt.Println("doccount:" + strconv.FormatInt(doccount, 10))
	return
}

//今日待追踪线索count for customMgr A类
func (clueMgr *ClueMgr) queryAClueOperatingTodayTraceClueCountForCustomMgr(customMgr string) (acluetracecount int64, err error) {

	var (
		ctx context.Context
		// results  []bson.M
		// doccount int64
	)
	ctx, _ = context.WithTimeout(context.Background(), 10*time.Second)

	if acluetracecount, err = clueMgr.clueCollection.CountDocuments(ctx, bson.M{"clueStatus": "跟进中", "customMgr": customMgr, "clueType": "A类:意向强烈", "nextTraceDate": bson.M{"$lte": common.BuildDateTodayStr2()}}, &options.CountOptions{}); err != nil {
		acluetracecount = 0
	}
	// fmt.Println("doccount:" + strconv.FormatInt(doccount, 10))
	return
}

//今日待追踪线索count for customMgr B类
func (clueMgr *ClueMgr) queryBClueOperatingTodayTraceClueCountForCustomMgr(customMgr string) (bcluetracecount int64, err error) {

	var (
		ctx context.Context
		// results  []bson.M
		// doccount int64
	)
	ctx, _ = context.WithTimeout(context.Background(), 10*time.Second)

	if bcluetracecount, err = clueMgr.clueCollection.CountDocuments(ctx, bson.M{"clueStatus": "跟进中", "customMgr": customMgr, "clueType": "B类:中等意向", "nextTraceDate": bson.M{"$lte": common.BuildDateTodayStr2()}}, &options.CountOptions{}); err != nil {
		bcluetracecount = 0
	}
	// fmt.Println("doccount:" + strconv.FormatInt(doccount, 10))
	return
}

//今日待追踪线索count for customMgr C类
func (clueMgr *ClueMgr) queryCClueOperatingTodayTraceClueCountForCustomMgr(customMgr string) (ccluetracecount int64, err error) {

	var (
		ctx context.Context
		// results  []bson.M
		// doccount int64
	)
	ctx, _ = context.WithTimeout(context.Background(), 10*time.Second)

	if ccluetracecount, err = clueMgr.clueCollection.CountDocuments(ctx, bson.M{"clueStatus": "跟进中", "customMgr": customMgr, "clueType": "C类:意向不明", "nextTraceDate": bson.M{"$lte": common.BuildDateTodayStr2()}}, &options.CountOptions{}); err != nil {
		ccluetracecount = 0
	}
	// fmt.Println("doccount:" + strconv.FormatInt(doccount, 10))
	return
}

//今日待追踪线索count for customMgr E类
func (clueMgr *ClueMgr) queryEClueOperatingTodayTraceClueCountForCustomMgr(customMgr string) (ecluetracecount int64, err error) {

	var (
		ctx context.Context
		// results  []bson.M
		// doccount int64
	)
	ctx, _ = context.WithTimeout(context.Background(), 10*time.Second)

	if ecluetracecount, err = clueMgr.clueCollection.CountDocuments(ctx, bson.M{"clueStatus": "跟进中", "customMgr": customMgr, "clueType": "E类:对接同行", "nextTraceDate": bson.M{"$lte": common.BuildDateTodayStr2()}}, &options.CountOptions{}); err != nil {
		ecluetracecount = 0
	}
	// fmt.Println("doccount:" + strconv.FormatInt(doccount, 10))
	return
}

//今日待追踪线索count for customMgr 获得线索
func (clueMgr *ClueMgr) queryHDClueOperatingTodayTraceClueCountForCustomMgr(customMgr string) (hdcluetracecount int64, err error) {

	var (
		ctx context.Context
		// results  []bson.M
		// doccount int64
	)
	ctx, _ = context.WithTimeout(context.Background(), 10*time.Second)

	if hdcluetracecount, err = clueMgr.clueCollection.CountDocuments(ctx, bson.M{"clueStatus": "跟进中", "customMgr": customMgr, "clueType": "获得线索", "nextTraceDate": bson.M{"$lte": common.BuildDateTodayStr2()}}, &options.CountOptions{}); err != nil {
		hdcluetracecount = 0
	}
	// fmt.Println("doccount:" + strconv.FormatInt(doccount, 10))
	return
}

//今日待追踪线索A类
func (clueMgr *ClueMgr) queryAClueOperatingTodayTraceClueCount() (acluetracecount int64, err error) {

	var (
		ctx context.Context
		// results  []bson.M
		// doccount int64
	)
	ctx, _ = context.WithTimeout(context.Background(), 10*time.Second)

	if acluetracecount, err = clueMgr.clueCollection.CountDocuments(ctx, bson.M{"clueStatus": "跟进中", "clueType": "A类:意向强烈", "nextTraceDate": bson.M{"$lte": common.BuildDateTodayStr2()}}, &options.CountOptions{}); err != nil {
		acluetracecount = 0
	}
	// fmt.Println("doccount:" + strconv.FormatInt(doccount, 10))
	return
}

//今日待追踪线索B类
func (clueMgr *ClueMgr) queryBClueOperatingTodayTraceClueCount() (bcluetracecount int64, err error) {

	var (
		ctx context.Context
		// results  []bson.M
		// doccount int64
	)
	ctx, _ = context.WithTimeout(context.Background(), 10*time.Second)

	if bcluetracecount, err = clueMgr.clueCollection.CountDocuments(ctx, bson.M{"clueStatus": "跟进中", "clueType": "B类:中等意向", "nextTraceDate": bson.M{"$lte": common.BuildDateTodayStr2()}}, &options.CountOptions{}); err != nil {
		bcluetracecount = 0
	}
	// fmt.Println("doccount:" + strconv.FormatInt(doccount, 10))
	return
}

//今日待追踪线索 C类
func (clueMgr *ClueMgr) queryCClueOperatingTodayTraceClueCount() (ccluetracecount int64, err error) {

	var (
		ctx context.Context
		// results  []bson.M
		// doccount int64
	)
	ctx, _ = context.WithTimeout(context.Background(), 10*time.Second)

	if ccluetracecount, err = clueMgr.clueCollection.CountDocuments(ctx, bson.M{"clueStatus": "跟进中", "clueType": "C类:意向不明", "nextTraceDate": bson.M{"$lte": common.BuildDateTodayStr2()}}, &options.CountOptions{}); err != nil {
		ccluetracecount = 0
	}
	// fmt.Println("doccount:" + strconv.FormatInt(doccount, 10))
	return
}

//今日待追踪线索 E类
func (clueMgr *ClueMgr) queryEClueOperatingTodayTraceClueCount() (ecluetracecount int64, err error) {

	var (
		ctx context.Context
		// results  []bson.M
		// doccount int64
	)
	ctx, _ = context.WithTimeout(context.Background(), 10*time.Second)

	if ecluetracecount, err = clueMgr.clueCollection.CountDocuments(ctx, bson.M{"clueStatus": "跟进中", "clueType": "E类:对接同行", "nextTraceDate": bson.M{"$lte": common.BuildDateTodayStr2()}}, &options.CountOptions{}); err != nil {
		ecluetracecount = 0
	}
	// fmt.Println("doccount:" + strconv.FormatInt(doccount, 10))
	return
}

//今日待追踪线索获得线索
func (clueMgr *ClueMgr) queryHDClueOperatingTodayTraceClueCount() (hdcluetracecount int64, err error) {

	var (
		ctx context.Context
		// results  []bson.M
		// doccount int64
	)
	ctx, _ = context.WithTimeout(context.Background(), 10*time.Second)

	if hdcluetracecount, err = clueMgr.clueCollection.CountDocuments(ctx, bson.M{"clueStatus": "跟进中", "clueType": "获得线索", "nextTraceDate": bson.M{"$lte": common.BuildDateTodayStr2()}}, &options.CountOptions{}); err != nil {
		hdcluetracecount = 0
	}
	// fmt.Println("doccount:" + strconv.FormatInt(doccount, 10))
	return
}

// 今日待追踪线索count  "orderStatus": bson.M{"$ne": "已废弃"}
func (clueMgr *ClueMgr) queryOperatingTodayTraceClueCount() (todaytracecount int64, err error) {

	var (
		ctx context.Context
		// results  []bson.M
		// doccount int64
	)
	ctx, _ = context.WithTimeout(context.Background(), 10*time.Second)

	if todaytracecount, err = clueMgr.clueCollection.CountDocuments(ctx, bson.M{"clueStatus": "跟进中", "clueType": bson.M{"$ne": "E类:对接同行"}, "nextTraceDate": bson.M{"$lte": common.BuildDateTodayStr2()}}, &options.CountOptions{}); err != nil {
		todaytracecount = 0
	}
	// fmt.Println("doccount:" + strconv.FormatInt(doccount, 10))
	return
}

//今日线索count  for IncustomMgr
func (clueMgr *ClueMgr) getOperatingCuleSumTodayForInCustomMgr() (doccount int64, err error) {

	if doccount, err = clueMgr.clueCollection.CountDocuments(context.TODO(), bson.M{"clueType": bson.M{"$ne": "E类:对接同行"}, "createTime": bson.M{"$regex": common.BuildDateTodayStr2(), "$options": "$i"}, "channelType": "内部员工发掘"}, &options.CountOptions{}); err != nil {
		doccount = 0
	}

	return
}

//今日线索count  for customMgr
func (clueMgr *ClueMgr) getOperatingCuleSumTodayForCustomMgr(customMgr string) (doccount int64, err error) {

	if doccount, err = clueMgr.clueCollection.CountDocuments(context.TODO(), bson.M{"clueType": bson.M{"$ne": "E类:对接同行"}, "createTime": bson.M{"$regex": common.BuildDateTodayStr2(), "$options": "$i"}, "customMgr": customMgr}, &options.CountOptions{}); err != nil {
		doccount = 0
	}

	return
}

//今日线索count
func (clueMgr *ClueMgr) getOperatingCuleSumToday() (doccount int64, err error) {

	if doccount, err = clueMgr.clueCollection.CountDocuments(context.TODO(), bson.M{"clueType": bson.M{"$ne": "E类:对接同行"}, "createTime": bson.M{"$regex": common.BuildDateTodayStr2(), "$options": "$i"}}, &options.CountOptions{}); err != nil {
		doccount = 0
	}

	return
}

// 不等于
// query := collection.Find(bson.M{"x": bson.M{"$ne": 3}})

//本月线索count for Incustom
func (clueMgr *ClueMgr) getOperatingCuleSumMonForInCustom() (doccount int64, err error) {

	if doccount, err = clueMgr.clueCollection.CountDocuments(context.TODO(), bson.M{"clueType": bson.M{"$ne": "E类:对接同行"}, "createTime": bson.M{"$regex": common.BuildDateMonStr2(), "$options": "$i"}, "channelType": "内部员工发掘"}, &options.CountOptions{}); err != nil {
		doccount = 0
	}
	return
}

//本月线索count for custom
func (clueMgr *ClueMgr) getOperatingCuleSumMonForCustom(customMgr string) (doccount int64, err error) {

	if doccount, err = clueMgr.clueCollection.CountDocuments(context.TODO(), bson.M{"clueType": bson.M{"$ne": "E类:对接同行"}, "createTime": bson.M{"$regex": common.BuildDateMonStr2(), "$options": "$i"}, "customMgr": customMgr}, &options.CountOptions{}); err != nil {
		doccount = 0
	}
	return
}

//本月线索count
func (clueMgr *ClueMgr) getOperatingCuleSumMon() (doccount int64, err error) {

	if doccount, err = clueMgr.clueCollection.CountDocuments(context.TODO(), bson.M{"clueType": bson.M{"$ne": "E类:对接同行"}, "createTime": bson.M{"$regex": common.BuildDateMonStr2(), "$options": "$i"}}, &options.CountOptions{}); err != nil {
		doccount = 0
	}
	return
}

//本月营销发掘线索
func (clueMgr *ClueMgr) getOperatingClueYXMon() (doccount int64, err error) {

	if doccount, err = clueMgr.clueCollection.CountDocuments(context.TODO(), bson.M{"createTime": bson.M{"$regex": common.BuildDateMonStr2(), "$options": "$i"}, "channelType": "营销发掘"}, &options.CountOptions{}); err != nil {
		doccount = 0
	}
	return
}

// 本月销售发掘线索
func (clueMgr *ClueMgr) getOperatingCuleXSMon() (doccount int64, err error) {

	if doccount, err = clueMgr.clueCollection.CountDocuments(context.TODO(), bson.M{"createTime": bson.M{"$regex": common.BuildDateMonStr2(), "$options": "$i"}, "channelType": "销售发掘"}, &options.CountOptions{}); err != nil {
		doccount = 0
	}
	return
}

// 本月内部员工发掘线索
func (clueMgr *ClueMgr) getOperatingCuleNBYGMon() (doccount int64, err error) {

	if doccount, err = clueMgr.clueCollection.CountDocuments(context.TODO(), bson.M{"createTime": bson.M{"$regex": common.BuildDateMonStr2(), "$options": "$i"}, "channelType": "内部员工发掘"}, &options.CountOptions{}); err != nil {
		doccount = 0
	}
	return
}

// 本月抖音线索
func (clueMgr *ClueMgr) getOperatingCuleDYMon() (doccount int64, err error) {

	if doccount, err = clueMgr.clueCollection.CountDocuments(context.TODO(), bson.M{"createTime": bson.M{"$regex": common.BuildDateMonStr2(), "$options": "$i"}, "saleChannel": "抖音推广"}, &options.CountOptions{}); err != nil {
		doccount = 0
		// fmt.Println(err)
	}
	return
}

// 本月百度线索
func (clueMgr *ClueMgr) getOperatingCuleBDMon() (doccount int64, err error) {

	if doccount, err = clueMgr.clueCollection.CountDocuments(context.TODO(), bson.M{"createTime": bson.M{"$regex": common.BuildDateMonStr2(), "$options": "$i"}, "saleChannel": "百度"}, &options.CountOptions{}); err != nil {
		doccount = 0
		// fmt.Println(err)
	}
	return
}

// 本月58同城线索
func (clueMgr *ClueMgr) getOperatingCule58Mon() (doccount int64, err error) {

	if doccount, err = clueMgr.clueCollection.CountDocuments(context.TODO(), bson.M{"createTime": bson.M{"$regex": common.BuildDateMonStr2(), "$options": "$i"}, "saleChannel": "58同城"}, &options.CountOptions{}); err != nil {
		doccount = 0
	}
	return
}

func (clueMgr *ClueMgr) queryOperatingFloor(custommgr string) (err error) {

	var (
		ctx     context.Context
		results []bson.M
	)
	ctx, _ = context.WithTimeout(context.Background(), 10*time.Second)

	// fmt.Println(common.BuildDateTodayMonStr())
	pipeline := mongo.Pipeline{

		{{"$match", bson.D{{"clueNo", bsonx.Regex("2012", "im")}}}},
		{{"$group", bson.D{{"_id", "$channelType"}, {"count", bson.D{{"$sum", 1}}}}}},
		// {{"$match", bson.D{{"clueNo", bson.M{"$regex": common.BuildDateTodayStr()}}}}},
		// {{"$match", bson.D{{"clueNo", bson.D{"$regex", "2012"}}}}},
	}

	cursor, err := G_clueMgr.clueCollection.Aggregate(ctx, pipeline)
	// fmt.Println(err.Error())
	defer cursor.Close(ctx)

	if err = cursor.All(context.TODO(), &results); err != nil {
		log.Fatal(err)
	}

	// for _, result := range results {
	// 	fmt.Println(result["_id"])
	// 	fmt.Println(result["count"])
	// }

	// fmt.Println("doccount:" + strconv.FormatInt(doccount, 10))
	return
}

func handleDrawEntClueInfo(resp http.ResponseWriter, req *http.Request) {
	var (
		err         error
		bytes       []byte
		companyname string
		// entcluests  string
		custommgr string
		drawdate  string
		// rolelimit     *common.RoleLimits
	)

	if err = req.ParseForm(); err != nil {
		goto ERR
	}
	companyname = req.PostForm.Get("companyname")
	custommgr = req.PostForm.Get("custommgr")
	drawdate = req.PostForm.Get("drawdate")

	if err = G_clueMgr.updEntClueMgr(companyname, custommgr, drawdate); err == nil {
		if bytes, err = common.BuildResponse(0, "success", "更新企业线索客户经理成功"); err == nil {
			resp.Write(bytes)
		}
	} else {
		goto ERR
	}

	return
ERR:
	if bytes, err = common.BuildResponse(-1, err.Error(), nil); err == nil {
		resp.Write(bytes)
	}
}

func handleUpdEntClueSts(resp http.ResponseWriter, req *http.Request) {
	var (
		err         error
		bytes       []byte
		companyname string
		entcluests  string
		dropinfo    string
		// rolelimit     *common.RoleLimits
	)

	if err = req.ParseForm(); err != nil {
		goto ERR
	}
	companyname = req.PostForm.Get("companyname")
	entcluests = req.PostForm.Get("entcluests")
	dropinfo = req.PostForm.Get("dropinfo")

	if err = G_clueMgr.updEntClueSts(companyname, entcluests, dropinfo); err == nil {
		if bytes, err = common.BuildResponse(0, "success", "更新企业线索状态成功"); err == nil {
			resp.Write(bytes)
		}
	} else {
		goto ERR
	}

	return
ERR:
	if bytes, err = common.BuildResponse(-1, err.Error(), nil); err == nil {
		resp.Write(bytes)
	}
}

func handleTraceEntClue(resp http.ResponseWriter, req *http.Request) {
	var (
		err             error
		bytes           []byte
		entClueTrace    *common.EntTraceClue
		entClue         *common.EntClue
		entcluetracestr string
		// rolelimit     *common.RoleLimits
	)

	if err = req.ParseForm(); err != nil {
		goto ERR
	}
	entcluetracestr = req.PostForm.Get("entcluetraceinfo")
	if err = json.Unmarshal([]byte(entcluetracestr), &entClueTrace); err != nil {
		goto ERR
	}

	if entClueTrace.BusinessId != "" && entClueTrace.CompanyName != "" {
		entClue = G_clueMgr.entClueFilter(entClueTrace.BusinessId, entClueTrace.CompanyName)
		if entClue != nil {
			G_clueMgr.entClueUpd(entClueTrace)
			if bytes, err = common.BuildResponse(-1, err.Error(), "企业线索Trace成功"); err == nil {
				resp.Write(bytes)
			}
		}
	} else {
		if bytes, err = common.BuildResponse(-1, err.Error(), "公司名称和营业执照编号，不可为空"); err == nil {
			resp.Write(bytes)
		}
	}

	return
ERR:
	if bytes, err = common.BuildResponse(-1, err.Error(), nil); err == nil {
		resp.Write(bytes)
	}
}

func (clueMgr *ClueMgr) getCuleSumToday() (doccount int64, err error) {

	if doccount, err = clueMgr.clueCollection.CountDocuments(context.TODO(), bson.M{"clueNo": bson.M{"$regex": common.BuildDateTodayStr(), "$options": "$i"}}, &options.CountOptions{}); err != nil {
		doccount = 0
	}

	return
}

func (clueMgr *ClueMgr) dropClue(clueNo string, dropInfo string, dropReason string) (err error) {

	var (
		// resultOne *mongo.InsertOneResult
		filter *common.ClueIdFilter
		// update *common.HostInfo
		traceDate  string
		clueStatus string
		clueType   string
	)

	filter = &common.ClueIdFilter{
		ClueNo: clueNo,
	}

	traceDate = common.BuildTimeNowStr()
	clueStatus = "废弃"
	clueType = common.CLUESTS_DROP

	// fmt.Println(clueNo, dropInfo)
	clueMgr.clueCollection.FindOneAndUpdate(context.TODO(), filter, bson.M{"$set": bson.M{"dropReason": dropReason, "dropInfo": dropInfo, "traceDate": traceDate, "clueStatus": clueStatus, "clueType": clueType}})

	// fmt.Println("doccount:" + strconv.FormatInt(doccount, 10))
	return
}

func (clueMgr *ClueMgr) entClueFilter(companyname string, bussid string) (entclue *common.EntClue) {

	// fmt.Println(clueNo, dropInfo)
	clueMgr.entclueCollection.FindOne(context.TODO(), bson.M{"companyName": companyname, "businessId": bussid}).Decode(&entclue)

	// fmt.Println("doccount:" + strconv.FormatInt(doccount, 10))
	return
}

func (clueMgr *ClueMgr) entClueUpd(entTraceclue *common.EntTraceClue) (err error) {

	// fmt.Println(clueNo, dropInfo)
	clueMgr.entclueCollection.FindOneAndUpdate(context.TODO(), bson.M{"companyName": entTraceclue.CompanyName, "businessId": entTraceclue.BusinessId}, entTraceclue)
	// fmt.Println("doccount:" + strconv.FormatInt(doccount, 10))
	return
}

func (clueMgr *ClueMgr) delClue(clueNo string) (err error) {

	var (
		// resultOne *mongo.InsertOneResult
		filter *common.ClueIdFilter
		// update *common.HostInfo
	)

	filter = &common.ClueIdFilter{
		ClueNo: clueNo,
	}

	_, err = clueMgr.clueCollection.DeleteOne(context.TODO(), filter, &options.DeleteOptions{})

	// fmt.Println("doccount:" + strconv.FormatInt(doccount, 10))
	return
}

func (clueMgr *ClueMgr) updClueV(clueno string) (err error) {

	var (
		// resultOne *mongo.InsertOneResult
		filter   *common.ClueIdFilter
		doccount int64
		// bsonClueInfo bson.M
		// update *common.HostInfo
	)

	filter = &common.ClueIdFilter{
		ClueNo: clueno,
	}

	if doccount, err = clueMgr.clueCollection.CountDocuments(context.TODO(), filter, &options.CountOptions{}); err != nil {
		return
	}
	// fmt.Println("doccount:" + strconv.FormatInt(doccount, 10))
	// fmt.Println(clueInfo)
	if doccount > 0 {
		clueMgr.clueCollection.FindOneAndUpdate(context.TODO(), filter, bson.M{"$set": bson.M{"clueStatus": "已成单", "clueType": common.CLUESTS_ORDER}})
	}

	return
}

func (clueMgr *ClueMgr) updClue(clueUpdInfo *common.TraceUpdClue) (err error) {

	var (
		// resultOne *mongo.InsertOneResult
		filter   *common.ClueIdFilter
		doccount int64
		// bsonClueInfo bson.M
		// update *common.HostInfo
	)

	filter = &common.ClueIdFilter{
		ClueNo: clueUpdInfo.ClueNo,
	}

	if doccount, err = clueMgr.clueCollection.CountDocuments(context.TODO(), filter, &options.CountOptions{}); err != nil {
		return
	}
	// fmt.Println("doccount:" + strconv.FormatInt(doccount, 10))
	// fmt.Println(clueInfo)
	if doccount > 0 {
		clueMgr.clueCollection.FindOneAndUpdate(context.TODO(), filter, bson.M{"$set": clueUpdInfo})
	}

	return
}

func (clueMgr *ClueMgr) saveEntClue(entclueInfo *common.EntClue) (err error) {

	var (
		// resultOne *mongo.InsertOneResult
		doccount int64
		// update *common.HostInfo
	)
	if doccount, err = clueMgr.entclueCollection.CountDocuments(context.TODO(), bson.M{"companyName": entclueInfo.CompanyName}, &options.CountOptions{}); err != nil {
		return
	}
	entclueInfo.CreateDate = common.BuildTimeNowStr()
	if doccount > 0 {
		clueMgr.entclueCollection.UpdateOne(context.TODO(), bson.M{"companyName": entclueInfo.CompanyName}, bson.M{"$set": entclueInfo})
	} else {
		clueMgr.entclueCollection.InsertOne(context.TODO(), entclueInfo)
	}

	return
}

func (clueMgr *ClueMgr) updEntClueMgr(companyname string, cluemgr string, drawdate string) (err error) {

	var (
	// resultOne *mongo.InsertOneResult
	// doccount int64
	// update *common.HostInfo
	)
	_, err = clueMgr.entclueCollection.UpdateOne(context.TODO(), bson.M{"companyName": companyname}, bson.M{"$set": bson.M{"customMgr": cluemgr, "companyInfoStatus": "已领取", "drawDate": drawdate}})

	// clueMgr.entclueCollection.InsertOne(context.TODO(), entclueInfo)

	return
}

func (clueMgr *ClueMgr) updEntClueSts(companyname string, clueSts string, dropinfo string) (err error) {

	var (
	// resultOne *mongo.InsertOneResult
	// doccount int64
	// update *common.HostInfo
	)
	_, err = clueMgr.entclueCollection.UpdateOne(context.TODO(), bson.M{"companyName": companyname}, bson.M{"$set": bson.M{"companyInfoStatus": clueSts, "dropInfo": dropinfo}})

	// clueMgr.entclueCollection.InsertOne(context.TODO(), entclueInfo)

	return
}

func (clueMgr *ClueMgr) saveClue(clueInfo *common.Clue) (err error) {

	var (
		// resultOne *mongo.InsertOneResult
		filter   *common.ClueIdFilter
		doccount int64
		// update *common.HostInfo
	)

	filter = &common.ClueIdFilter{
		ClueNo: clueInfo.ClueNo,
	}

	if doccount, err = clueMgr.clueCollection.CountDocuments(context.TODO(), filter, &options.CountOptions{}); err != nil {
		return
	}

	// fmt.Println("doccount:" + strconv.FormatInt(doccount, 10))

	if doccount > 0 {
		clueMgr.clueCollection.UpdateOne(context.TODO(), filter, bson.M{"$set": clueInfo})
	} else {
		clueMgr.clueCollection.InsertOne(context.TODO(), clueInfo)
	}

	return
}

func (clueMgr *ClueMgr) queryClueByNo(clueNo string) (clueInfo *common.Clue, err error) {

	var (
		// resultOne *mongo.InsertOneResult
		filter *common.ClueIdFilter
		result *mongo.SingleResult

		// update *common.HostInfo
	)
	// fmt.Println("clueNo:", clueNo)

	filter = &common.ClueIdFilter{
		ClueNo: clueNo,
	}

	result = clueMgr.clueCollection.FindOne(context.TODO(), filter, &options.FindOneOptions{})
	result.Decode(&clueInfo)
	// fmt.Println("clueInfo:", clueInfo)
	return
}

func (clueMgr *ClueMgr) countCluebySet(setElements bson.M) (countClue int64, err error) {
	var (
		// resultOne *mongo.InsertOneResult
		ctx context.Context
		// update *common.HostInfo
	)
	// fmt.Println(setElements)

	ctx, _ = context.WithTimeout(context.Background(), 15*time.Second)
	if len(setElements["$and"].([]primitive.M)) == 0 {
		// fmt.Println(0)
		countClue, err = clueMgr.clueCollection.CountDocuments(ctx, bson.D{})
	} else {
		// fmt.Println(1)
		countClue, err = clueMgr.clueCollection.CountDocuments(ctx, setElements)
	}
	return
}

func (clueMgr *ClueMgr) countEntCluebySet(setElements bson.M) (countClue int64, err error) {
	var (
		// resultOne *mongo.InsertOneResult
		ctx context.Context
		// update *common.HostInfo
	)
	// fmt.Println(setElements)

	ctx, _ = context.WithTimeout(context.Background(), 15*time.Second)
	if len(setElements["$and"].([]primitive.M)) == 0 {
		// fmt.Println(0)
		countClue, err = clueMgr.entclueCollection.CountDocuments(ctx, bson.M{})
	} else {
		// fmt.Println(1)
		countClue, err = clueMgr.entclueCollection.CountDocuments(ctx, setElements)
	}
	return
}
func (clueMgr *ClueMgr) queryEntCluebySet(setElements bson.M, skip int64, limit int64) (entclues []*common.EntClue, err error) {

	var (
		// resultOne *mongo.InsertOneResult
		cursor      *mongo.Cursor
		entclueinfo *common.EntClue
		findopt     *options.FindOptions
		ctx         context.Context
		clueSort    *common.SortEntClue
		// update *common.HostInfo
	)

	ctx, _ = context.WithTimeout(context.Background(), 10*time.Second)

	findopt = &options.FindOptions{}
	clueSort = &common.SortEntClue{
		SortOrder: -1,
	}
	findopt.SetSort(clueSort)

	if limit > 0 && skip >= 0 {
		findopt.SetLimit(limit)
		findopt.SetSkip(limit * skip)

	} else {
		return
	}

	// fmt.Println(len(setElements["$and"].([]primitive.M)))
	// fmt.Println(setElements.Map())
	// fmt.Println(setElements)
	if len(setElements["$and"].([]primitive.M)) == 0 {
		// fmt.Println(0)
		cursor, err = clueMgr.entclueCollection.Find(context.TODO(), bson.M{}, findopt)
	} else {
		// fmt.Println(1)
		cursor, err = clueMgr.entclueCollection.Find(context.TODO(), setElements, findopt)
	}
	defer cursor.Close(ctx)

	for cursor.Next(ctx) {
		entclueinfo = &common.EntClue{}
		if err = cursor.Decode(entclueinfo); err != nil {
			continue
		}
		entclues = append(entclues, entclueinfo)
	}
	// fmt.Println("doccount:" + strconv.FormatInt(doccount, 10))
	return
}

func (clueMgr *ClueMgr) queryFeiqiCluebySet(setElements bson.M, skip int64, limit int64) (clueInfo []*common.Clue, err error) {

	var (
		// resultOne *mongo.InsertOneResult
		cursor   *mongo.Cursor
		clueinfo *common.Clue
		findopt  *options.FindOptions
		ctx      context.Context
		clueSort *common.SortByTraceDate
		// update *common.HostInfo
	)

	ctx, _ = context.WithTimeout(context.Background(), 10*time.Second)

	findopt = &options.FindOptions{}
	clueSort = &common.SortByTraceDate{
		SortOrder: -1,
	}
	findopt.SetSort(clueSort)

	if limit > 0 && skip >= 0 {
		findopt.SetLimit(limit)
		findopt.SetSkip(limit * skip)

	} else {
		return
	}

	// fmt.Println(len(setElements["$and"].([]primitive.M)))
	// fmt.Println(setElements.Map())
	// fmt.Println(setElements)
	if len(setElements["$and"].([]primitive.M)) == 0 {
		// fmt.Println(0000000)
		cursor, err = clueMgr.clueCollection.Find(context.TODO(), bson.D{}, findopt)
	} else {
		// fmt.Println(1111111)
		cursor, err = clueMgr.clueCollection.Find(context.TODO(), setElements, findopt)
	}
	defer cursor.Close(ctx)

	for cursor.Next(ctx) {
		clueinfo = &common.Clue{}
		if err = cursor.Decode(clueinfo); err != nil {
			continue
		}
		// fmt.Println(clueinfo)
		clueInfo = append(clueInfo, clueinfo)
	}
	// fmt.Println("doccount:" + strconv.FormatInt(doccount, 10))
	return
}

func (clueMgr *ClueMgr) queryCluebySet(setElements bson.M, skip int64, limit int64) (clueInfo []*common.Clue, err error) {

	var (
		// resultOne *mongo.InsertOneResult
		cursor   *mongo.Cursor
		clueinfo *common.Clue
		findopt  *options.FindOptions
		ctx      context.Context
		clueSort *common.SortLogByClueNo
		// update *common.HostInfo
	)

	ctx, _ = context.WithTimeout(context.Background(), 10*time.Second)

	findopt = &options.FindOptions{}
	clueSort = &common.SortLogByClueNo{
		SortOrder: -1,
	}
	findopt.SetSort(clueSort)

	if limit > 0 && skip >= 0 {
		findopt.SetLimit(limit)
		findopt.SetSkip(limit * skip)

	} else {
		return
	}

	// fmt.Println(len(setElements["$and"].([]primitive.M)))
	// fmt.Println(setElements.Map())
	// fmt.Println(setElements)
	if len(setElements["$and"].([]primitive.M)) == 0 {
		// fmt.Println(0000000)
		cursor, err = clueMgr.clueCollection.Find(context.TODO(), bson.D{}, findopt)
	} else {
		// fmt.Println(1111111)
		cursor, err = clueMgr.clueCollection.Find(context.TODO(), setElements, findopt)
	}
	defer cursor.Close(ctx)

	for cursor.Next(ctx) {
		clueinfo = &common.Clue{}
		if err = cursor.Decode(clueinfo); err != nil {
			continue
		}
		// fmt.Println(clueinfo)
		clueInfo = append(clueInfo, clueinfo)
	}
	// fmt.Println("doccount:" + strconv.FormatInt(doccount, 10))
	return
}

func (clueMgr *ClueMgr) queryClueDownloadbySet(setElements bson.M) (clueinfos []*common.Clue, err error) {

	var (
		// resultOne *mongo.InsertOneResult
		cursor   *mongo.Cursor
		clueinfo *common.Clue
		findopt  *options.FindOptions
		ctx      context.Context
		clueSort *common.SortLogByClueNo
		// update *common.HostInfo
	)

	ctx, _ = context.WithTimeout(context.Background(), 60*time.Second)

	findopt = &options.FindOptions{}
	clueSort = &common.SortLogByClueNo{
		SortOrder: -1,
	}
	findopt.SetSort(clueSort)
	// findopt.SetLimit(10000)
	// findopt.SetSkip(0)
	findopt.SetBatchSize(3000)

	if len(setElements["$and"].([]primitive.M)) == 0 {
		// fmt.Println(0000000)
		cursor, err = clueMgr.clueCollection.Find(context.TODO(), bson.D{}, findopt)
	} else {
		cursor, err = clueMgr.clueCollection.Find(context.TODO(), setElements, findopt)
	}
	defer cursor.Close(ctx)

	// cursor.Decode(&clueinfos)
	// var i int
	for cursor.Next(ctx) {
		clueinfo = &common.Clue{}
		if err = cursor.Decode(clueinfo); err != nil {
			fmt.Println(err.Error())
			continue
		}
		// i = i + 1
		// fmt.Println(i)
		// fmt.Println(clueinfo)
		clueinfo.CluePhone = ""
		clueinfos = append(clueinfos, clueinfo)
	}
	// fmt.Println("doccount:" + strconv.FormatInt(doccount, 10))
	return
}

func handleQueryClueInfoOutOfLine(resp http.ResponseWriter, req *http.Request) {
	var (
		err         error
		bytes       []byte
		salechannel string
		busstype    string
		channeltype string
		custommgr   string
		custommgrs  []string
		dept        string
		querySet    []bson.M
		skipParam   string
		limitParam  string
		skip        int
		limit       int
		clueinfos   []*common.Clue
		countclue   int64
		begindate   string
		enddate     string
		// rolelimit     *common.RoleLimits

		queryBson bson.M

		// bdquery   bson.D

		contractname string
		cluephone    string

		cluetype   string
		cluetypes  []string
		dropinfo   string
		createuser string
		salemon    string
		saleday    string
	)

	query := req.URL.Query()
	skipParam = query.Get("skip")
	limitParam = query.Get("limit")

	if skip, err = strconv.Atoi(skipParam); err != nil {
		skip = 0
	}

	if limit, err = strconv.Atoi(limitParam); err != nil {
		limit = 100
	}

	salechannel = query.Get("salechannel")
	busstype = query.Get("busstype")
	channeltype = query.Get("channeltype")
	custommgr = query.Get("custommgr")
	custommgrs = strings.Split(custommgr, ",")
	dept = query.Get("dept")
	begindate = query.Get("begindate")
	enddate = query.Get("enddate")
	skipParam = query.Get("skip")
	limitParam = query.Get("limit")

	contractname = query.Get("contractname")
	createuser = query.Get("createuser")
	cluephone = query.Get("cluephone")
	cluetype = query.Get("cluetype")
	cluetypes = strings.Split(cluetype, ",")
	dropinfo = query.Get("dropinfo")

	salemon = query.Get("salemon")
	saleday = query.Get("saleday")

	if dropinfo != "" {
		q_dropInfo := bson.M{"dropInfo": dropinfo}
		querySet = append(querySet, q_dropInfo)
	}

	if createuser != "" {
		q_createUser := bson.M{"createUser": createuser}
		querySet = append(querySet, q_createUser)
	}

	// "clueType": bson.M{"$ne": "E类:对接同行"}, "nextTraceDate": bson.M{"$lte": common.BuildDateTodayStr2()}

	if cluetype != "" {

		// fmt.Println(cluetype)
		// fmt.Println(cluetypes)
		q_clueType := bson.M{"clueType": bson.M{"$in": cluetypes}}
		querySet = append(querySet, q_clueType)
	}

	q_clueType2 := bson.M{"clueType": bson.M{"$ne": "E类:对接同行"}}
	querySet = append(querySet, q_clueType2)
	// if cluestatus != "" {
	// 	q_clueStatus := bson.M{"clueStatus": cluestatus}
	// 	querySet = append(querySet, q_clueStatus)
	// }

	//20201212====201212
	if saleday != "" {
		q_cluePhone := bson.M{"clueNo": bson.M{"$regex": common.BuildDateTodayStr(), "$options": "$i"}}
		querySet = append(querySet, q_cluePhone)
	}

	//20201212====2012
	if salemon != "" {
		q_cluePhone := bson.M{"clueNo": bson.M{"$regex": common.BuildDateTodayMonStr(), "$options": "$i"}}
		querySet = append(querySet, q_cluePhone)
	}

	if cluephone != "" {
		q_cluePhone := bson.M{"cluePhone": cluephone}
		querySet = append(querySet, q_cluePhone)
	}

	if contractname != "" {
		q_contractName := bson.M{"contractName": bson.M{"$regex": contractname, "$options": "$i"}}
		querySet = append(querySet, q_contractName)
	}

	if salechannel != "" {
		q_saleChannel := bson.M{"saleChannel": salechannel}
		querySet = append(querySet, q_saleChannel)
	}
	if busstype != "" {
		q_bussType := bson.M{"bussType": busstype}
		querySet = append(querySet, q_bussType)
	}

	if channeltype != "" {
		q_channelType := bson.M{"channelType": channeltype}
		querySet = append(querySet, q_channelType)
	}

	if custommgr != "" {
		// fmt.Println(custommgrs)
		q_customMgr := bson.M{"customMgr": bson.M{"$in": custommgrs}}
		querySet = append(querySet, q_customMgr)
	}

	if dept != "" {
		q_dept := bson.M{"dept": dept}
		querySet = append(querySet, q_dept)
	}

	if begindate != "" {
		q_begindate := bson.M{"createTime": bson.M{"$gte": begindate}}
		querySet = append(querySet, q_begindate)
		// setElements = append(setElements, bson.E{"createTime", createtime})
	}

	if enddate != "" {
		q_enddate := bson.M{"createTime": bson.M{"$lte": enddate}}
		querySet = append(querySet, q_enddate)
		// setElements = append(setElements, bson.E{"createTime", createtime})
	}

	q_cluestatus := bson.M{"clueStatus": "跟进中"}
	querySet = append(querySet, q_cluestatus)

	q_begintracedate := bson.M{"nextTraceDate": bson.M{"$lt": common.BuildDateTodayStr2()}}
	querySet = append(querySet, q_begintracedate)

	q_tracedatenotnull := bson.M{"nextTraceDate": bson.M{"$gte": ""}}
	querySet = append(querySet, q_tracedatenotnull)

	queryBson = bson.M{"$and": querySet}

	countclue, _ = G_clueMgr.countCluebySet(queryBson)

	cluemap := make(map[string]interface{})

	// fmt.Println(countclue)

	if clueinfos, err = G_clueMgr.queryCluebySet(queryBson, int64(skip), int64(limit)); err != nil {
		goto ERR
	}

	// if getfile == "yes" {
	// 	outFile = "./downloadfile/clue" + common.BuildDateTodayStr4() + ".xlsx"
	// 	f := xlsx.NewFile()
	// 	sheet, _ := f.AddSheet("clue")
	// 	for idx, _ := range clueinfos {
	// 		// fmt.Println(idx)
	// 		row := sheet.AddRow()
	// 		clueinfo = clueinfos[idx]

	// 		row.WriteStruct(clueinfo, -1)
	// 	}

	// 	if err = f.Save(outFile); err != nil {
	// 		goto ERR
	// 	}
	// }

	cluemap["cluecount"] = countclue
	cluemap["clueinfos"] = clueinfos
	if bytes, err = common.BuildResponse(0, "success", cluemap); err == nil {
		resp.Write(bytes)
	} else {
		goto ERR
	}

	return
ERR:
	if bytes, err = common.BuildResponse(-1, err.Error(), nil); err == nil {
		resp.Write(bytes)
	}
}

func handleQueryClueInfo2(resp http.ResponseWriter, req *http.Request) {
	var (
		err         error
		bytes       []byte
		clueNo      string
		salechannel string
		busstype    string
		channeltype string
		custommgr   string
		custommgrs  []string
		cluestatuss []string
		dept        string
		clueinfo    *common.Clue
		querySet    []bson.M
		skipParam   string
		limitParam  string
		skip        int
		limit       int
		clueinfos   []*common.Clue
		countclue   int64
		begindate   string
		enddate     string
		// rolelimit     *common.RoleLimits

		queryBson bson.M

		// bdquery   bson.D

		contractname string
		cluephone    string

		cluestatus     string
		cluetype       string
		cluetypes      []string
		dropinfo       string
		createuser     string
		begintracedate string
		endtracedate   string
		salemon        string
		saleday        string
	)

	query := req.URL.Query()
	clueNo = query.Get("clueno")
	salechannel = query.Get("salechannel")
	busstype = query.Get("busstype")
	channeltype = query.Get("channeltype")
	custommgr = query.Get("custommgr")
	custommgrs = strings.Split(custommgr, ",")
	dept = query.Get("dept")
	begindate = query.Get("begindate")
	enddate = query.Get("enddate")
	skipParam = query.Get("skip")
	limitParam = query.Get("limit")

	contractname = query.Get("contractname")
	createuser = query.Get("createuser")
	cluephone = query.Get("cluephone")
	cluestatus = query.Get("cluestatus")
	cluestatuss = strings.Split(cluestatus, ",")
	cluetype = query.Get("cluetype")
	cluetypes = strings.Split(cluetype, ",")
	dropinfo = query.Get("dropinfo")

	salemon = query.Get("salemon")
	saleday = query.Get("saleday")

	begintracedate = query.Get("begintracedate")
	endtracedate = query.Get("endtracedate")

	if skip, err = strconv.Atoi(skipParam); err != nil {
		skip = 0
	}

	if limit, err = strconv.Atoi(limitParam); err != nil {
		limit = 100
	}

	if clueNo != "" {
		clueinfo, _ = G_clueMgr.queryClueByNo(clueNo)
		if bytes, err = common.BuildResponse(0, "success", clueinfo); err == nil {
			resp.Write(bytes)
		} else {
			goto ERR
		}
		return
	} else {

		if dropinfo != "" {
			q_dropInfo := bson.M{"dropInfo": dropinfo}
			querySet = append(querySet, q_dropInfo)
		}

		if createuser != "" {
			q_createUser := bson.M{"createUser": createuser}
			querySet = append(querySet, q_createUser)
		}

		if cluetype != "" {

			fmt.Println(cluetype)
			fmt.Println(cluetypes)
			q_clueType := bson.M{"clueType": bson.M{"$in": cluetypes}}
			querySet = append(querySet, q_clueType)
		}
		// if cluestatus != "" {
		// 	q_clueStatus := bson.M{"clueStatus": cluestatus}
		// 	querySet = append(querySet, q_clueStatus)
		// }

		//20201212====201212
		if saleday != "" {
			q_cluePhone := bson.M{"clueNo": bson.M{"$regex": common.BuildDateTodayStr(), "$options": "$i"}}
			querySet = append(querySet, q_cluePhone)
		}

		//20201212====2012
		if salemon != "" {
			q_cluePhone := bson.M{"clueNo": bson.M{"$regex": common.BuildDateTodayMonStr(), "$options": "$i"}}
			querySet = append(querySet, q_cluePhone)
		}

		if cluephone != "" {
			q_cluePhone := bson.M{"cluePhone": cluephone}
			querySet = append(querySet, q_cluePhone)
		}

		if contractname != "" {
			q_contractName := bson.M{"contractName": bson.M{"$regex": contractname, "$options": "$i"}}
			querySet = append(querySet, q_contractName)
		}

		if salechannel != "" {
			q_saleChannel := bson.M{"saleChannel": salechannel}
			querySet = append(querySet, q_saleChannel)
		}
		if busstype != "" {
			q_bussType := bson.M{"bussType": busstype}
			querySet = append(querySet, q_bussType)
		}

		if channeltype != "" {
			q_channelType := bson.M{"channelType": channeltype}
			querySet = append(querySet, q_channelType)
		}

		if custommgr != "" {
			// fmt.Println(custommgrs)
			q_customMgr := bson.M{"customMgr": bson.M{"$in": custommgrs}}
			querySet = append(querySet, q_customMgr)
		}

		if cluestatus != "" {
			// fmt.Println(cluestatuss)
			q_clueStatus := bson.M{"clueStatus": bson.M{"$in": cluestatuss}}
			querySet = append(querySet, q_clueStatus)
		}

		if dept != "" {
			q_dept := bson.M{"dept": dept}
			querySet = append(querySet, q_dept)
		}

		if begindate != "" {
			q_begindate := bson.M{"createTime": bson.M{"$gte": begindate}}
			querySet = append(querySet, q_begindate)
			// setElements = append(setElements, bson.E{"createTime", createtime})
		}

		if enddate != "" {
			q_enddate := bson.M{"createTime": bson.M{"$lte": enddate}}
			querySet = append(querySet, q_enddate)
			// setElements = append(setElements, bson.E{"createTime", createtime})
		}

		if begintracedate != "" {
			q_begintracedate := bson.M{"nextTraceDate": bson.M{"$gte": begintracedate}}
			querySet = append(querySet, q_begintracedate)
			// setElements = append(setElements, bson.E{"createTime", createtime})
		}

		if endtracedate != "" {
			q_endtracedate := bson.M{"nextTraceDate": bson.M{"$lte": endtracedate}}
			querySet = append(querySet, q_endtracedate)
			// setElements = append(setElements, bson.E{"createTime", createtime})
		}

		queryBson = bson.M{"$and": querySet}

		countclue, _ = G_clueMgr.countCluebySet(queryBson)

		// fmt.Println(countclue)

		if "废弃" == cluestatus {
			if clueinfos, err = G_clueMgr.queryFeiqiCluebySet(queryBson, int64(skip), int64(limit)); err != nil {
				goto ERR
			}
		} else {
			if clueinfos, err = G_clueMgr.queryCluebySet(queryBson, int64(skip), int64(limit)); err != nil {
				goto ERR
			}
		}

		// if getfile == "yes" {
		// 	outFile = "./downloadfile/clue" + common.BuildDateTodayStr4() + ".xlsx"
		// 	f := xlsx.NewFile()
		// 	sheet, _ := f.AddSheet("clue")
		// 	for idx, _ := range clueinfos {
		// 		// fmt.Println(idx)
		// 		row := sheet.AddRow()
		// 		clueinfo = clueinfos[idx]

		// 		row.WriteStruct(clueinfo, -1)
		// 	}

		// 	if err = f.Save(outFile); err != nil {
		// 		goto ERR
		// 	}
		// }

		cluemap := make(map[string]interface{})
		cluemap["cluecount"] = countclue
		cluemap["clueinfos"] = clueinfos
		if bytes, err = common.BuildResponse(0, "success", cluemap); err == nil {
			resp.Write(bytes)
		} else {
			goto ERR
		}
	}

	return
ERR:
	if bytes, err = common.BuildResponse(-1, err.Error(), nil); err == nil {
		resp.Write(bytes)
	}
}

func handleDownloadClueInfo(resp http.ResponseWriter, req *http.Request) {
	var (
		outfile     string
		err         error
		bytes       []byte
		clueNo      string
		salechannel string
		busstype    string
		channeltype string
		custommgr   string
		custommgrs  []string
		cluestatuss []string
		dept        string
		clueinfo    *common.Clue
		querySet    []bson.M
		// skipParam   string
		// limitParam  string
		// skip        int
		// limit       int
		clueinfos []*common.Clue
		// countclue int64
		begindate string
		enddate   string
		// rolelimit     *common.RoleLimits

		queryBson bson.M

		// bdquery   bson.D

		contractname string
		cluephone    string

		cluestatus     string
		cluetype       string
		dropinfo       string
		createuser     string
		begintracedate string
		endtracedate   string
		salemon        string
		saleday        string
		x              interface{}
		row            *xlsx.Row
	)

	query := req.URL.Query()
	clueNo = query.Get("clueno")
	salechannel = query.Get("salechannel")
	busstype = query.Get("busstype")
	channeltype = query.Get("channeltype")
	custommgr = query.Get("custommgr")
	custommgrs = strings.Split(custommgr, ",")
	dept = query.Get("dept")
	begindate = query.Get("begindate")
	enddate = query.Get("enddate")
	contractname = query.Get("contractname")
	createuser = query.Get("createuser")
	cluephone = query.Get("cluephone")
	cluestatus = query.Get("cluestatus")
	cluestatuss = strings.Split(cluestatus, ",")
	cluetype = query.Get("cluetype")
	dropinfo = query.Get("dropinfo")

	salemon = query.Get("salemon")
	saleday = query.Get("saleday")

	begintracedate = query.Get("begintracedate")
	endtracedate = query.Get("endtracedate")

	cluemap := make(map[string]interface{})

	if clueNo != "" {
		q_clueNo := bson.M{"clueNo": clueNo}
		querySet = append(querySet, q_clueNo)
	}

	if dropinfo != "" {
		q_dropInfo := bson.M{"dropInfo": dropinfo}
		querySet = append(querySet, q_dropInfo)
	}
	if createuser != "" {
		q_createUser := bson.M{"createUser": createuser}
		querySet = append(querySet, q_createUser)
	}
	if cluetype != "" {
		q_clueType := bson.M{"clueType": cluetype}
		querySet = append(querySet, q_clueType)
	}
	// if cluestatus != "" {
	// 	q_clueStatus := bson.M{"clueStatus": cluestatus}
	// 	querySet = append(querySet, q_clueStatus)
	// }

	//20201212====201212
	if saleday != "" {
		q_cluePhone := bson.M{"clueNo": bson.M{"$regex": common.BuildDateTodayStr(), "$options": "$i"}}
		querySet = append(querySet, q_cluePhone)
	}

	//20201212====2012
	if salemon != "" {
		q_cluePhone := bson.M{"clueNo": bson.M{"$regex": common.BuildDateTodayMonStr(), "$options": "$i"}}
		querySet = append(querySet, q_cluePhone)
	}

	if cluephone != "" {
		q_cluePhone := bson.M{"cluePhone": cluephone}
		querySet = append(querySet, q_cluePhone)
	}

	if contractname != "" {
		q_contractName := bson.M{"contractName": bson.M{"$regex": contractname, "$options": "$i"}}
		querySet = append(querySet, q_contractName)
	}

	if salechannel != "" {
		q_saleChannel := bson.M{"saleChannel": salechannel}
		querySet = append(querySet, q_saleChannel)
	}
	if busstype != "" {
		q_bussType := bson.M{"bussType": busstype}
		querySet = append(querySet, q_bussType)
	}

	if channeltype != "" {
		q_channelType := bson.M{"channelType": channeltype}
		querySet = append(querySet, q_channelType)
	}

	if custommgr != "" {
		// fmt.Println(custommgrs)
		q_customMgr := bson.M{"customMgr": bson.M{"$in": custommgrs}}
		querySet = append(querySet, q_customMgr)
	}

	if cluestatus != "" {
		// fmt.Println(cluestatuss)
		q_clueStatus := bson.M{"clueStatus": bson.M{"$in": cluestatuss}}
		querySet = append(querySet, q_clueStatus)
	}

	if dept != "" {
		q_dept := bson.M{"dept": dept}
		querySet = append(querySet, q_dept)
	}

	if begindate != "" {
		q_begindate := bson.M{"createTime": bson.M{"$gte": begindate}}
		querySet = append(querySet, q_begindate)
		// setElements = append(setElements, bson.E{"createTime", createtime})
	}

	if enddate != "" {
		q_enddate := bson.M{"createTime": bson.M{"$lte": enddate}}
		querySet = append(querySet, q_enddate)
		// setElements = append(setElements, bson.E{"createTime", createtime})
	}

	if begintracedate != "" {
		q_begintracedate := bson.M{"nextTraceDate": bson.M{"$gte": begintracedate}}
		querySet = append(querySet, q_begintracedate)
		// setElements = append(setElements, bson.E{"createTime", createtime})
	}

	if endtracedate != "" {
		q_endtracedate := bson.M{"nextTraceDate": bson.M{"$lte": endtracedate}}
		querySet = append(querySet, q_endtracedate)
		// setElements = append(setElements, bson.E{"createTime", createtime})
	}

	queryBson = bson.M{"$and": querySet}

	if clueinfos, err = G_clueMgr.queryClueDownloadbySet(queryBson); err != nil {
		// goto ERR
	}

	outfile = "./downloadfile/clue" + common.BuildDateTodayStr4() + ".xlsx"
	f := xlsx.NewFile()

	sheet, _ := f.AddSheet("clue")
	for idx, _ := range clueinfos {

		// fmt.Println(idx)
		//写表头
		// fmt.Println(1111 + idx)
		if idx == 0 {
			// fmt.Println(idx)
			x = clueinfos[idx]
			row = sheet.AddRow()
			// reflect.ValueOf(custominfo)
			// v := reflect.ValueOf(&custominfo)
			// n := reflect.ValueOf(&custominfo).NumField()
			t := reflect.TypeOf(x)
			if t.Kind() == reflect.Ptr {
				t = t.Elem()
			}
			// fmt.Println(t.Kind())
			if t.Kind() != reflect.Struct {
				fmt.Println("Check type error not Struct")
				return
			}
			n := t.NumField()
			for i := 0; i < n; i = i + 1 {
				cell := row.AddCell()
				cell.SetValue(t.Field(i).Tag.Get("uname"))
			}
		}

		row = sheet.AddRow()
		clueinfo = clueinfos[idx]
		row.WriteStruct(clueinfo, -1)
	}

	// row.WriteSlice(clueinfos, -1)

	// f.Save(outfile)

	if err = f.Save(outfile); err != nil {
		goto ERR
	}

	// time.Sleep(10 * time.Second)

	// cluemap["cluecount"] = countclue
	// cluemap["filepath"] = outfile[1:]
	cluemap["filepath"] = G_config.FileUrl + ":" + strconv.Itoa(G_config.ApiPort) + "/downloadfile/clue" + common.BuildDateTodayStr4() + ".xlsx"

	if bytes, err = common.BuildResponse(0, "success", cluemap); err == nil {
		resp.Write(bytes)
	} else {
		goto ERR
	}

	return
ERR:
	if bytes, err = common.BuildResponse(-1, err.Error(), nil); err == nil {
		resp.Write(bytes)
	}

	// return
}

func handleQueryEntClueInfo(resp http.ResponseWriter, req *http.Request) {
	var (
		err         error
		bytes       []byte
		companyname string
		buildregion string
		domforfunds string
		infofrom    string
		// entclueinfo *common.EntClue
		querySet   []bson.M
		skipParam  string
		limitParam string
		skip       int
		limit      int
		clueinfos  []*common.EntClue
		countclue  int64
		// rolelimit     *common.RoleLimits

		queryBson bson.M

		// bdquery   bson.D

		createbegindate string
		createenddate   string

		beginbuilddate    string
		endbuilddate      string
		companyinfostatus string
		custommgr         string
	)

	query := req.URL.Query()
	companyname = query.Get("companyname")
	buildregion = query.Get("buildregion")
	domforfunds = query.Get("domforfunds")
	createbegindate = query.Get("createbegindate")
	createenddate = query.Get("createenddate")
	infofrom = query.Get("infofrom")
	beginbuilddate = query.Get("beginbuilddate")
	endbuilddate = query.Get("endbuilddate")
	skipParam = query.Get("skip")
	limitParam = query.Get("limit")
	companyinfostatus = query.Get("companyinfostatus")
	custommgr = query.Get("custommgr")

	if skip, err = strconv.Atoi(skipParam); err != nil {
		skip = 0
	}

	if limit, err = strconv.Atoi(limitParam); err != nil {
		limit = 100
	}

	if custommgr != "" {
		q_custommgr := bson.M{"customMgr": custommgr}
		querySet = append(querySet, q_custommgr)
	}

	if companyinfostatus != "" {
		q_companyinfostatus := bson.M{"companyInfoStatus": companyinfostatus}
		querySet = append(querySet, q_companyinfostatus)
	}

	if companyname != "" {
		q_companyName := bson.M{"companyName": bson.M{"$regex": companyname, "$options": "$i"}}
		querySet = append(querySet, q_companyName)
	}

	if buildregion != "" {
		q_buildRegion := bson.M{"buildRegion": buildregion}
		querySet = append(querySet, q_buildRegion)
	}
	if domforfunds != "" {
		q_domForFunds := bson.M{"domForFunds": domforfunds}
		querySet = append(querySet, q_domForFunds)
	}
	if infofrom != "" {
		q_infoFrom := bson.M{"infoFrom": infofrom}
		querySet = append(querySet, q_infoFrom)
	}

	if beginbuilddate != "" {
		q_begindate := bson.M{"buildDate": bson.M{"$gte": beginbuilddate}}
		querySet = append(querySet, q_begindate)
		// setElements = append(setElements, bson.E{"createTime", createtime})
	}

	if endbuilddate != "" {
		q_enddate := bson.M{"buildDate": bson.M{"$lte": endbuilddate}}
		querySet = append(querySet, q_enddate)
		// setElements = append(setElements, bson.E{"createTime", createtime})
	}

	if createbegindate != "" {
		q_begindate := bson.M{"createTime": bson.M{"$gte": createbegindate}}
		querySet = append(querySet, q_begindate)
		// setElements = append(setElements, bson.E{"createTime", createtime})
	}

	if createenddate != "" {
		q_enddate := bson.M{"createTime": bson.M{"$lte": createenddate}}
		querySet = append(querySet, q_enddate)
		// setElements = append(setElements, bson.E{"createTime", createtime})
	}

	queryBson = bson.M{"$and": querySet}

	cluemap := make(map[string]interface{})
	countclue, _ = G_clueMgr.countEntCluebySet(queryBson)
	// fmt.Println(countclue)
	if clueinfos, err = G_clueMgr.queryEntCluebySet(queryBson, int64(skip), int64(limit)); err != nil {
		goto ERR
	}
	cluemap["cluecount"] = countclue
	cluemap["clueinfos"] = clueinfos
	if bytes, err = common.BuildResponse(0, "success", cluemap); err == nil {
		resp.Write(bytes)
	} else {
		goto ERR
	}

	return
ERR:
	if bytes, err = common.BuildResponse(-1, err.Error(), nil); err == nil {
		resp.Write(bytes)
	}
}

func handleQueryEntClueInfotmp(resp http.ResponseWriter, req *http.Request) {
	var (
		err          error
		bytes        []byte
		clueNo       string
		salechannel  string
		busstype     string
		channeltype  string
		custommgr    string
		dept         string
		contractname string
		cluephone    string

		cluestatus  string
		cluetype    string
		dropinfo    string
		clueinfo    *common.Clue
		setElements bson.D
		// skipParam   string
		// limitParam  string
		createtime string
		// skip        int
		// limit       int
		clueinfos []*common.Clue
		countclue int64
		// begindata   string
		// enddata     string
		// rolelimit     *common.RoleLimits

		// queryBson []bson.D
		// bdquery   bson.D
	)

	query := req.URL.Query()
	clueNo = query.Get("clueno")
	salechannel = query.Get("salechannel")
	busstype = query.Get("busstype")
	channeltype = query.Get("channeltype")
	custommgr = query.Get("custommgr")
	dept = query.Get("dept")
	createtime = query.Get("createtime")
	custommgr = query.Get("custommgr")
	dept = query.Get("dept")
	contractname = query.Get("contractname")
	cluephone = query.Get("cluephone")
	cluestatus = query.Get("cluestatus")
	cluetype = query.Get("cluetype")
	dropinfo = query.Get("dropinfo")

	// begindata = query.Get("begindata")
	// enddata = query.Get("enddata")
	// skipParam = query.Get("skip")
	// limitParam = query.Get("limit")

	// if skip, err = strconv.Atoi(skipParam); err != nil {
	// 	skip = 0
	// }

	// if limit, err = strconv.Atoi(limitParam); err != nil {
	// 	limit = 100
	// }

	if clueNo != "" {
		clueinfo, _ = G_clueMgr.queryClueByNo(clueNo)
		if bytes, err = common.BuildResponse(0, "success", clueinfo); err == nil {
			resp.Write(bytes)
		} else {
			goto ERR
		}
		return
	} else {
		if salechannel != "" {
			setElements = append(setElements, bson.E{"saleChannel", salechannel})
		}
		if busstype != "" {
			setElements = append(setElements, bson.E{"bussType", busstype})
		}
		if contractname != "" {
			setElements = append(setElements, bson.E{"contractName", contractname})
		}
		if cluephone != "" {
			setElements = append(setElements, bson.E{"cluePhone", cluephone})
		}
		if channeltype != "" {
			setElements = append(setElements, bson.E{"channelType", channeltype})
		}
		if cluestatus != "" {
			setElements = append(setElements, bson.E{"clueStatus", cluestatus})
		}
		if cluetype != "" {
			setElements = append(setElements, bson.E{"clueType", cluetype})
		}
		if dropinfo != "" {
			setElements = append(setElements, bson.E{"dropInfo", dropinfo})
		}
		if custommgr != "" {
			setElements = append(setElements, bson.E{"customMgr", custommgr})
		}
		if dept != "" {
			setElements = append(setElements, bson.E{"dept", dept})
		}

		if createtime != "" {
			setElements = append(setElements, bson.E{"createTime", createtime})
		}

		// if begindata != "" {
		// 	bdquery = bson.D{{"createTime", bson.D{{"$gte", begindata}}}}
		// }
		// if enddata != "" {
		// 	setElements = append(setElements, bson.E{"createTime", bson.E{"$lte", begindata}})
		// }

		// q2 := bson.D{{"createTime": bson.D{{"gte": begindata}}}}

		// queryBson = append(queryBson, bdquery)
		// queryBson = append(queryBson, setElements)
		// countclue, _ = G_clueMgr.countCluebySet(setElements)

		// if clueinfos, err = G_clueMgr.queryCluebySet(setElements, int64(skip), int64(limit)); err != nil {
		// 	goto ERR
		// }
		cluemap := make(map[string]interface{})
		cluemap["cluecount"] = countclue
		cluemap["clueinfos"] = clueinfos
		if bytes, err = common.BuildResponse(0, "success", cluemap); err == nil {
			resp.Write(bytes)
		} else {
			goto ERR
		}
	}

	return
ERR:
	if bytes, err = common.BuildResponse(-1, err.Error(), nil); err == nil {
		resp.Write(bytes)
	}
}

func handleDelClueInfo(resp http.ResponseWriter, req *http.Request) {
	var (
		err    error
		bytes  []byte
		clueNo string

		// rolelimit     *common.RoleLimits
	)

	query := req.URL.Query()
	clueNo = query.Get("clueno")
	// fmt.Println(clueNo)

	// fmt.Println(clueinfo)
	if err = G_clueMgr.delClue(clueNo); err == nil {
		if bytes, err = common.BuildResponse(0, "success", "删除线索成功"); err == nil {
			resp.Write(bytes)
		}
	} else {
		goto ERR
	}
	return
ERR:
	if bytes, err = common.BuildResponse(-1, err.Error(), nil); err == nil {
		resp.Write(bytes)
	}
}

func handleDropClueInfo(resp http.ResponseWriter, req *http.Request) {
	var (
		err        error
		bytes      []byte
		clueNo     string
		dropInfo   string
		dropReason string

		// rolelimit     *common.RoleLimits
	)

	switch req.Method {

	case "GET":
		//io.WriteString(w, s string) 将字符串的
	case "POST":
		clueNo = req.PostFormValue("clueno")
		dropInfo = req.PostFormValue("dropinfo")
		dropReason = req.PostFormValue("dropreason")

	}
	// fmt.Println(clueNo)

	// fmt.Println(clueinfo)
	if err = G_clueMgr.dropClue(clueNo, dropInfo, dropReason); err == nil {
		if bytes, err = common.BuildResponse(0, "success", "废弃线索成功"); err == nil {
			resp.Write(bytes)
		}
	} else {
		goto ERR
	}
	return
ERR:
	if bytes, err = common.BuildResponse(-1, err.Error(), nil); err == nil {
		resp.Write(bytes)
	}
}

func handleEntClueInfo(resp http.ResponseWriter, req *http.Request) {
	var (
		err            error
		bytes          []byte
		entclueinfo    *common.EntClue
		entclueinfostr string

		// rolelimit     *common.RoleLimits
	)

	if err = req.ParseForm(); err != nil {
		goto ERR
	}
	entclueinfostr = req.PostForm.Get("entclueinfo")

	if err = json.Unmarshal([]byte(entclueinfostr), &entclueinfo); err != nil {
		goto ERR
	}

	// fmt.Println(clueinfo)
	if err = G_clueMgr.saveEntClue(entclueinfo); err == nil {
		if bytes, err = common.BuildResponse(0, "success", entclueinfo); err == nil {
			resp.Write(bytes)
		}
	} else {
		if bytes, err = common.BuildResponse(-1, "error", "新增线索异常"); err == nil {
			resp.Write(bytes)
		}
	}

	return
ERR:
	if bytes, err = common.BuildResponse(-1, err.Error(), nil); err == nil {
		resp.Write(bytes)
	}
}

func handleClueInfo(resp http.ResponseWriter, req *http.Request) {
	var (
		err         error
		bytes       []byte
		clueinfo    *common.Clue
		clueinfostr string
		clueSum     int64
		clueNo      string

		// rolelimit     *common.RoleLimits
	)

	if err = req.ParseForm(); err != nil {
		goto ERR
	}
	clueinfostr = req.PostForm.Get("clueinfo")

	if err = json.Unmarshal([]byte(clueinfostr), &clueinfo); err != nil {
		goto ERR
	}

	if clueinfo.ClueNo == "" {
		clueSum, _ = G_clueMgr.getCuleSumToday()
		clueNo = "XS" + common.BuildDateTodayStr() + strconv.FormatInt(clueSum+1, 10)
		clueinfo.ClueNo = clueNo
		clueinfo.CreateTime = common.BuildDateTodayStr2()
		//新增线索的时候，默认下次追踪日期为今天
		clueinfo.NextTraceDate = common.BuildDateTodayStr2()
	} else if clueinfo.ClueNo != "" {
		if clueinfo.NextTraceDate == "" {
			clueinfo.NextTraceDate = common.BuildDateTodayStr2()
		}
	}

	// fmt.Println(clueinfo)
	if err = G_clueMgr.saveClue(clueinfo); err == nil {
		if bytes, err = common.BuildResponse(0, "success", clueinfo); err == nil {
			resp.Write(bytes)
		}
	} else {
		if bytes, err = common.BuildResponse(-1, "error", "新增线索异常"); err == nil {
			resp.Write(bytes)
		}
	}

	return
ERR:
	if bytes, err = common.BuildResponse(-1, err.Error(), nil); err == nil {
		resp.Write(bytes)
	}
}

func InitClueMgr() (err error) {

	G_clueMgr = &ClueMgr{
		client:            G_MongoMgr.client,
		clueCollection:    G_MongoMgr.MongdbConnect.Collection("clue"),
		entclueCollection: G_MongoMgr.MongdbConnect.Collection("entclue"),
	}

	return
}
